﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;

namespace DNA.Mvc.jQuery
{
    public class DialogButtonFactory : CollectionFactory<DialogButton>
    {
        private Dialog dialog;
        //private AjaxHelper helper;

        protected IViewDataContainer ViewDataContainer { get; set; }

        protected ViewContext ViewContext { get; set; }

        public DialogButtonFactory(List<DialogButton> buttons, Dialog _parent, ViewContext viewContext, IViewDataContainer viewContainer)
            : base(buttons)
        {
            dialog = _parent;
            this.ViewContext = viewContext;
            this.ViewDataContainer = viewContainer;
        }

        public DialogButton AddClose()
        {
            return AddClose("Close");
        }

        public DialogButton AddClose(string text)
        {
            var button = new DialogButton()
            {
                Text = text,
                OnClick = getCloseScript()
            };
            Items.Add(button);
            return button;
        }

        private string getCloseScript()
        {
            return "$(\"#" + dialog.Name + "\").dialog('close');";
        }

        public DialogButton Add(string text, string click)
        {
            var button = new DialogButton() { Text = text, OnClick = click };
            Items.Add(button);
            return button;
        }

        public DialogButton AddLoad(string text, string url)
        {
            return AddAction(text, url, "GET", "");
        }

        public DialogButton AddLoad(string text, string url, string onSuccess)
        {
            return AddAction(text, url, "GET", onSuccess);
        }

        public DialogButton AddPost(string text, string url)
        {
            return AddAction(text, url, "GET", "");
        }

        public DialogButton AddPost(string text, string url, string onSuccess)
        {
            return AddAction(text, url, "POST", onSuccess);
        }

        public DialogButton AddAction(string text, string url, string httpMethod, string onSuccess)
        {
            var helper = new AjaxHelper(this.ViewContext, this.ViewDataContainer);
            var method = string.IsNullOrEmpty(httpMethod) ? "GET" : httpMethod;
            var click=helper.GeneratejQueryAjaxScripts(new jQueryAjaxOptions()
            {
                HttpMethod = method,
                AutoHandlingError = false,
                Url = url,
                OnSuccess = string.IsNullOrEmpty(onSuccess) ? getCloseScript() : onSuccess
            });
            return Add(text, click);
        }
    }
}
